<template>
    <el-card class="box-card">
        <template #header>
            <el-row>
                <el-button type="primary" :icon="Plus" @click="handleAdd">添加账户</el-button>
                <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
            </el-row>
        </template>

        <el-table :data="state.tableData" :empty-text="state.empty">
            <el-table-column type="selection" width="38" />
            <el-table-column label="头像" width="52" align="center">
                <template #default="scope">
                    <span class="avatar"><el-avatar shape="square" :size="23" :src="scope.row.avatar" /></span>
                </template>
            </el-table-column>
            <el-table-column prop="user" label="账户" show-overflow-tooltip />
            <el-table-column label="角色" width="250">
                <template #default="scope">
                    <span class="permission">
                        <el-tag v-for="item in scope.row.permission" :key="item.id">
                            {{ item.title }}
                        </el-tag>
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="电话" />
            <el-table-column prop="mail" label="邮箱" />
            <el-table-column fixed="right" label="状态" align="center" width="54">
                <template #default="scope">
                    <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
                        @change="changeStatus(scope.row)" size="small" />
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="96" align="center">
                <template #default="scope">
                    <el-button link type="primary" @click="handleEdit(scope.row)" size="small">编辑</el-button>
                    <el-popconfirm title="确定要删除吗？" @confirm="handleDelete(scope.row)">
                        <template #reference>
                            <el-button link type="primary" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog v-model="state.dialogVisible" width="400px">
            <template #header>
                {{ state.isEdit ? '编辑账户' : '添加账户' }}
            </template>

            <el-form ref="ruleForm" :model="state.form" :rules="rules" status-icon label-width="50px">

                <el-form-item label="头像" prop="avatar">
                    <el-upload v-model="state.form.avatar" action="/api/php-admin/public/system/upload/index"
                        list-type="picture-card" :limit="1" name="image">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <el-form-item label="账户" prop="user">
                    <el-input v-model="state.form.user" placeholder="输入账户" />
                </el-form-item>
                <el-form-item v-if="!state.isEdit" label="密码" prop="pswd">
                    <el-input v-model="state.form.pswd" placeholder="输入密码" />
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="state.form.phone" placeholder="输入电话" />
                </el-form-item>
                <el-form-item label="邮箱" prop="mail">
                    <el-input v-model="state.form.mail" placeholder="输入邮箱" />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="state.form.role" multiple placeholder="选择角色" style="width: 100%">
                        <el-option v-for="item in state.roleData" :key="item.id" :label="item.title" :value="item.id" />
                    </el-select>
                </el-form-item>

            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="state.dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </el-card>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Request from '@/request'


const ruleForm = ref()

const defaultForm = {
    avatar: '',
    user: '',
    pswd: '',
    phone: '',
    mail: '',
    role: '',
    status: 0
}

const state = reactive({
    tableData: [],
    roleData: [],
    dialogVisible: false,
    isEdit: false,
    empty: '暂无数据',
    form: JSON.parse(JSON.stringify(defaultForm))
})

const rules = {
    user: [
        { required: true, message: '请输入账号！', trigger: ['blur'] },
        { min: 3, message: '长度不能低于3位！', trigger: ['blur'] }
    ],
    pswd: [
        { required: true, message: '请输入密码！', trigger: ['blur'] },
        { min: 3, message: '长度不能低于3位！', trigger: ['blur'] }
    ],
    role: [
        { required: true, message: '请选择角色！', trigger: ['blur'] }
    ]
}

const handleAdd = () => {
    state.isEdit = false
    state.dialogVisible = true
    state.form = JSON.parse(JSON.stringify(defaultForm))
}

const handleEdit = (row) => {
    state.isEdit = true
    state.dialogVisible = true
    state.form = JSON.parse(JSON.stringify(row))
    state.form.role = JSON.parse(row.role)
}

const handleDelete = (row) => {
    Request
        .post('system/account/delete', { id: row.id })
        .then(res => {
            if (res.code) {
                getDataList()
            }

            ElMessage({
                message: res.message,
                type: res.code ? 'error' : 'success'
            })
        })
        .catch((error) => {
            console.log('error', error)
        })
}

const changeStatus = (row) => {
    Request
        .post('system/account/field', { id: row.id, field: 'status', value: row.status ? 1 : 0 })
        .then(res => {
            getDataList()
            ElMessage({
                message: res.message,
                grouping: true,
                type: res.code ? 'error' : 'success'
            })
        })
        .catch((error) => {
            console.log('error', error)
        })
}

const handleBatchDelete = () => {
    nextTick(() => {
        const selection = tableRef.value.getSelectionRows()
        const ids = selection.map(item => item.id)
        if (ids.length) {
            ElMessageBox.confirm(
                '确定要批量删除吗？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(() => {
                handleDelete(ids)
            }).catch(() => {

            })

        } else {
            ElMessage({
                message: '请先选中一个！',
                grouping: true,
                type: 'warning'
            })
        }
    })
}

const submitForm = () => {
    if (!ruleForm) return
    ruleForm.value.validate(valid => {
        if (valid) {
            const url = state.isEdit ? 'system/account/edit' : 'system/account/add'
            Request
                .post(url, state.form)
                .then(res => {
                    if (!res.code) {
                        getDataList()
                        state.dialogVisible = false
                    }

                    ElMessage({
                        message: res.message,
                        type: res.code ? 'error' : 'success'
                    })
                })
                .catch((error) => {
                    console.log('error', error)
                })
        }
    })
}

const getRoleList = () => {
    Request
        .post('system/role/index')
        .then(res => {
            if (!res.code) {
                state.roleData = res.datas.data
            }
        })
        .catch((error) => {
            console.log('error', error)
        })
}

getRoleList()

const getDataList = () => {
    Request
        .post('system/account/index')
        .then((res) => {
            if (res.code) {
                state.empty = res.message
            } else {
                state.tableData = res.datas.data
            }
        })
        .catch((error) => {
            console.log('error', error)
        })
}

getDataList()
</script>
<style scoped>
.avatar {
    height: 23px;
    width: 23px;
    overflow: hidden;
    display: block;
}

:deep(.el-upload--picture-card) {
    width: 80px;
    height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 80px;
    height: 80px;
}

.permission .el-tag {
    margin-right: 10px;
}
</style>